package sse;

import org.atmosphere.config.service.AtmosphereHandlerService;
import org.atmosphere.cpr.AtmosphereResourceEvent;
import org.atmosphere.cpr.AtmosphereResponse;
import org.atmosphere.handler.OnMessage;
import org.atmosphere.interceptor.AtmosphereResourceLifecycleInterceptor;
import org.atmosphere.interceptor.BroadcastOnPostAtmosphereInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Date;

/**
 * Created by alex on 15-1-14.
 */
@AtmosphereHandlerService(
        path = "/chat",
        interceptors = {
                AtmosphereResourceLifecycleInterceptor.class,
                BroadcastOnPostAtmosphereInterceptor.class
        }
)
public class SSEAtmosphereHandler extends OnMessage<String> {


    private final Logger logger = LoggerFactory.getLogger(SSEAtmosphereHandler.class);
    
    public void onMessage(AtmosphereResponse response, String message) throws IOException {
        String author = message.substring(message.indexOf(":" + 2, message.indexOf(",") - 1));
        String chat = message.substring(message.lastIndexOf(":") + 2, message.length() - 2);
        
        response.getWriter().write(new Data(author,message).toString());
    }

    @Override
    public void onDisconnect(AtmosphereResponse response) throws IOException {
        AtmosphereResourceEvent event = response.resource().getAtmosphereResourceEvent();
        if (event.isCancelled()) {
            logger.info("Browser {} unexpectedly disconnected", response.resource().uuid());
        } else if (event.isClosedByClient()) {
            logger.info("Browser {} closed the connection", response.resource().uuid());
        }
    }

    private final static class Data{
        
        private final String text;
        private final String author;

        private Data(String text, String author) {
            this.text = text;
            this.author = author;
        }

        public String toString() {
            return "{ \"text\" : \"" + text + "\", \"author\" : \"" + author + "\" , \"time\" : " + new Date().getTime() + "}";
        }
    }
}
